<?php
/**
 * 用户信息
 */

namespace Home\Controller;

use Think\Controller;

class UserSettingController extends BaseController
{
    /**
     * 用户基本信息设置视图
     */
    Public function index()
    {
        $where = array('uid' => session('uid'));
        $field = array('username', 'truename', 'sex', 'location', 'constellation', 'intro', 'face_max','face_medium','face_mini');
        $user = M('userinfo')->field($field)->where($where)->find();
        $this->user = $user;
        $this->display();
    }

    /**
     * 修改用户基本信息
     */
    Public function editBasic()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }
        header('Content-Type:text/html;Charset=UTF-8');
        $data = array(
            'username' => I('post.nickname'),
            'truename' => I('post.truename'),
            'sex' => (int)$_POST['sex'],
            'location' => I('post.province') . ' ' . I('post.city'),
            'constellation' => I('post.night'),
            'intro' => I('post.intro')
        );
        $where = array('uid' => session('uid'));
        if (M('userinfo')->where($where)->save($data)) {
            $this->success('修改成功', U('index', '', ''));
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 修改用户头像
     */
    Public function editFace()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }
        $db = M('userinfo');
        $where = array('uid' => session('uid'));
        $field = array('face_mini','face_medium', 'face_max');
        $old = $db->where($where)->field($field)->find();
        if ($db->where($where)->save($_POST)) {
            if (!empty($old['face_medium'])) {
                @unlink($old['face_medium']);
                @unlink( $old['face_mini']);
                @unlink($old['face_max']);
            }
            $this->success('修改成功', U('index', '', ''));
        } else {
            $this->error('修改失败，请重试...');
        }
    }

    /**
     * 修改密码
     */
    Public function editPwd()
    {
        if (!IS_POST) {
            $this->error("非法请求");
        }

        $db = M('user');
        //验证旧密码
        $where = array('id' => session('uid'));
        $old = $db->where($where)->getField('password');

        if (md5(I('post.old')) != $old) {
            $this->error('旧密码错误');
        }

        if (I('post.new') != I('post.newed')) {
            $this->error('两次密码不一致');
        }

        $newPwd = md5(I('post.new'));
        $data = array(
            'id' => session('uid'),
            'password' => $newPwd
        );

        if ($db->save($data)) {
            $this->success('修改成功', U('index','',''));
        } else {
            $this->error('修改失败，请重试...');
        }
    }
}

?>